const Base = require("../base.js");

module.exports = class extends Base {
  /**
   * 列表
   * @param type
   * @param fid
   * @param field
   * @returns {Promise<any>}
   */
  async indexAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model("admin");
    let result = {};
    result.errno = 0;
    result.data = await db.list(post || {});
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<void>}
   */
  async delAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model("admin");
    let result = {};
    try {
      let { id } = post;
      if (typeof id === "number") id = "" + id;
      if (typeof id === "string" && id.includes(",")) id = id.split(",");
      await db.del(id);
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 添加
   * @returns {Promise<any>}
   */
  async addAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model("admin");
    let result = {};
    try {
      await db.add(post);
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 详情
   * @returns {Promise<any>}
   */
  async detailAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model("admin");
    let result = {};
    try {
      result.errno = 0;
      result.data = await db.find(post.id);
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 修改
   * @returns {Promise<any>}
   */
  async updateAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model("admin");
    let result = {};
    try {
      result.errno = 0;
      result.data = await db.where({ id: post.id }).update(post);
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }
};
